#include "util.hpp"
#include <cstdio>
#include <vector>
#include <functional>
#include <sys/select.h>
using namespace std;
using func_t = function<void()>;

void init(vector<func_t> &cbs)
{
    cbs.push_back(printLog);
    cbs.push_back(download);
    cbs.push_back(executeSql);
}

void doWork(const vector<func_t> &cbs)
{
    for (auto const &cb : cbs)
    {
        cb();
        sleep(3);
    }
}

int main()
{
    vector<func_t> cbs;
    init(cbs);
    setNonBlock(0);
    char buffer[1024];
    while (true)
    {
        // printf(">>> ");
        // fflush(stdout);

        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            // 我们在终端输入得时候输入为 111\n 若我们buffer[n]=0 结果 111\n\0 会多输出一个空格
            buffer[n - 1] = 0;
            cout << "echo# " << buffer << std::endl;
        }
        else if (n == 0)
        {
            cout << "read end" << endl;
            break;
        }
        else
        {   // -1
        //     11Resource temporarily unavailable
            // cout << n << endl;
            // cout << errno << strerror(errno) << endl;

            if(errno==EAGAIN)
            {
                cout<<"我没错 ，我只是没有数据"<<endl;
                doWork(cbs);
            }
            else if(errno==EINTR)
            {
                continue;
            }
            else
            {
                std::cout << "n : " << n << " errno: " << strerror(errno) << std::endl;
                break;
            }

        }
        sleep(1);
    }
    return 0;
}